<template>
    <!-- 搜索部分 -->
    <div class="search-box">
        <el-row>
            <el-col :span="9">
                <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>&nbsp;添加预约</el-button>
            </el-col>
            <el-col :span="5">
                <el-input v-model.trim="searchInfo.user" style="width: 240px" placeholder="请输入预约用户姓名" />
            </el-col>
            <el-col :span="3">
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-col>
        </el-row>
    </div>
    <!-- 表格部分 -->
    <div class="table-box">
        <el-table :data="currentTableData" style="width: 100%" height="450px" :header-cell-style="{ 'background-color': '#f5f7fa' }">
            <el-table-column prop="user" label="预约用户" width="120" />
            <el-table-column prop="counselor" label="咨询师" width="120" />
            <el-table-column prop="issue" label="咨询问题" width="120" />
            <el-table-column label="预约时段" width="180">
                <template #default="scope">
                    <div>{{ scope.row.startTime }}</div>
                    <div>{{ scope.row.endTime }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" />
            <el-table-column prop="cancelTime" label="取消时间" width="180" />
            <el-table-column prop="cancelReason" label="取消原因" width="180" />
            <el-table-column prop="notes" label="备注" min-width="180" />
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleConfirm(scope.row)" :disabled="scope.row.status === '已确认'">确认</el-button>
                    <el-button link type="danger" size="small" @click="handleCancel(scope.row)" :disabled="scope.row.status === '教师取消'">取消</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 添加预约对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加预约" width="35%">
        <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
            <el-form-item label="预约用户" prop="user">
                <span v-if="addForm.user" style="margin-right: 10px">{{ addForm.user }}</span>
                <el-button type="primary" @click="selectUserDialogVisible = true">
                    {{ addForm.user ? '重新选择' : '选择用户' }}
                </el-button>
            </el-form-item>
            <el-form-item label="咨询师" prop="counselor">
                <el-select v-model="addForm.counselor" placeholder="请选择咨询师">
                    <el-option v-for="c in counselorOptions" :key="c" :label="c" :value="c" />
                </el-select>
            </el-form-item>
            <el-form-item label="预约日期" prop="date">
                <el-date-picker v-model="addForm.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="预约时段" prop="timeRange">
                <el-time-picker
                    v-model="addForm.timeRange"
                    is-range
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="HH:mm"
                />
            </el-form-item>
            <el-form-item label="咨询问题" prop="issue">
                <el-select v-model="addForm.issue" placeholder="请选择咨询问题">
                    <el-option v-for="i in issueOptions" :key="i" :label="i" :value="i" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="addForm.notes" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveAdd">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 选择用户对话框 -->
    <el-dialog v-model="selectUserDialogVisible" title="选择用户" width="60%">
        <div class="select-user-dialog-content">
            <div class="tree-container">
                    <el-tree
                    ref="treeRef"
                    :data="treeData"
                    :props="treeProps"
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick"
                    default-expand-all
                />
            </div>
            <div class="search-container">
                <el-input v-model="searchKeyword" placeholder="搜索姓名或学号" class="search-input" clearable />
                <div class="selected-user-info">
                    <span>已选择：{{ selectedUser }}</span>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="selectUserDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmSelectUser">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 取消预约对话框 -->
    <el-dialog v-model="cancelDialogVisible" title="取消预约" width="30%">
        <el-form :model="cancelForm" ref="cancelFormRef" label-width="80px">
            <el-form-item label="取消原因">
                <el-input v-model="cancelForm.reason" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="confirmCancel">确认取消</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 分页部分 -->
    <div class="page-box">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="currentPageSize"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const tableData = ref([]);
const tableDataCopy = ref([]);
const currentTableData = ref([]);
const currentPage = ref(1);
const currentPageSize = ref(10);
const searchInfo = ref({ user: '' });

const addDialogVisible = ref(false);
const selectUserDialogVisible = ref(false); // 控制选择用户对话框
const cancelDialogVisible = ref(false);
const addFormRef = ref(null);
const searchKeyword = ref('');
const selectedUser = ref('');
const treeRef = ref(null);
let currentRow = null;

const cancelForm = ref({
    reason: ''
});

const treeData = ref([]);
const treeProps = {
    children: 'children',
    label: 'label'
};

const generateTreeData = () => {
    const colleges = ['信息工程学院', '机械工程学院'];
    const majors = ['软件工程', '网络工程', '物联网工程'];
    const grades = ['2021级', '2022级', '2023级', '2024级'];
    const classes = ['1班', '2班', '3班', '4班', '5班'];
    let studentIdCounter = 1;

    return colleges.map(college => ({
        label: college,
        children: majors.map(major => ({
            label: major,
            children: grades.map(grade => ({
                label: grade,
                children: classes.map(cls => ({
                    label: cls,
                    children: Array.from({ length: Math.floor(Math.random() * 2) + 2 }, (_, i) => ({
                        label: `学生${studentIdCounter}`,
                        id: `2024${String(studentIdCounter++).padStart(4, '0')}`
                    }))
                }))
            }))
        }))
    }));
};

watch(searchKeyword, (val) => {
    treeRef.value.filter(val);
});

const filterNode = (value, data) => {
    if (!value) return true;
    // Only filter student nodes
    if (data.children) return false;
    return data.label.includes(value) || (data.id && data.id.includes(value));
};

const rules = {
    user: [{ required: true, message: '请选择预约用户', trigger: 'change' }],
    counselor: [{ required: true, message: '请选择咨询师', trigger: 'change' }],
    date: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
    timeRange: [{ required: true, message: '请选择预约时段', trigger: 'change' }],
    issue: [{ required: true, message: '请选择咨询问题', trigger: 'change' }]
};

const addForm = ref({
    user: '',
    counselor: '',
    date: '',
    timeRange: ['', ''],
    issue: '',
    notes: ''
});

const counselorOptions = ['咨询师1', '咨询师2', '咨询师3'];
const issueOptions = ['学业压力', '家庭关系', '人际交往', '自我认知', '情绪管理', '个人成长', '职业生涯', '亲子关系'];

const handleSizeChange = (newPageSize) => {
  currentPageSize.value = newPageSize;
  updateCurrentTableData();
}
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  updateCurrentTableData();
}

const updateCurrentTableData = () => {
    const start = (currentPage.value - 1) * currentPageSize.value
    const end = start + currentPageSize.value
    currentTableData.value = tableData.value.slice(start, end)
}

const search = () => {
    if (!searchInfo.value.user) {
        tableData.value = [...tableDataCopy.value];
    } else {
        tableData.value = tableDataCopy.value.filter(item => item.user.includes(searchInfo.value.user));
    }
    currentPage.value = 1;
    updateCurrentTableData();
}
const reset = () => {
  searchInfo.value = { user: '' }
  tableData.value = [...tableDataCopy.value];
  currentPage.value = 1;
  updateCurrentTableData();
}

const loadDataFromSession = () => {
    const data = sessionStorage.getItem('appointmentData');
    if (data) {
        tableData.value = JSON.parse(data);
    } else {
        tableData.value = [
            {
                id: 1,
                user: '学生A',
                counselor: '咨询师1',
                issue: '学业压力',
                startTime: '2023-11-01 10:00',
                endTime: '2023-11-01 11:00',
                status: '未确认',
                cancelTime: '',
                cancelReason: '',
                notes: '首次咨询'
            }
        ];
    }
};

const saveDataToSession = () => {
    sessionStorage.setItem('appointmentData', JSON.stringify(tableData.value));
    tableDataCopy.value = [...tableData.value];
};

onMounted(() => {
    loadDataFromSession();
    tableDataCopy.value = [...tableData.value];
    updateCurrentTableData();
    treeData.value = generateTreeData();
});

const handleAdd = () => {
    addForm.value = {
        user: '',
        counselor: '',
        date: '',
        timeRange: null,
        issue: '',
        notes: ''
    };
    addDialogVisible.value = true;
};

const saveAdd = () => {
    addFormRef.value.validate((valid) => {
        if (valid) {
            const newAppointment = {
                id: Date.now(),
                user: addForm.value.user,
                counselor: addForm.value.counselor,
                issue: addForm.value.issue,
                startTime: `${addForm.value.date} ${addForm.value.timeRange ? addForm.value.timeRange[0] : ''}`,
                endTime: `${addForm.value.date} ${addForm.value.timeRange ? addForm.value.timeRange[1] : ''}`,
                status: '未确认',
                cancelTime: '',
                cancelReason: '',
                notes: addForm.value.notes
            };
            tableData.value.unshift(newAppointment);
            saveDataToSession();
            updateCurrentTableData();
            ElMessage.success('添加成功');
            addDialogVisible.value = false;
        } else {
            ElMessage.error('请填写所有必填项');
            return false;
        }
    });
};

const handleConfirm = (row) => {
    const item = tableData.value.find(item => item.id === row.id);
    if (item) {
        item.status = '已确认';
    }
    saveDataToSession();
    updateCurrentTableData();
    ElMessage.success('操作成功');
};

const handleCancel = (row) => {
    currentRow = row;
    cancelForm.value.reason = '';
    cancelDialogVisible.value = true;
};

const confirmCancel = () => {
    if (currentRow) {
        const item = tableData.value.find(item => item.id === currentRow.id);
        if (item) {
            item.status = '教师取消';
            item.cancelTime = new Date().toLocaleString();
            item.cancelReason = cancelForm.value.reason;
        }
        saveDataToSession();
        updateCurrentTableData();
        ElMessage.info('已取消预约');
        cancelDialogVisible.value = false;
    }
};

const handleNodeClick = (data) => {
    if (!data.children) { // Is a student node
        selectedUser.value = data.label;
    }
};

const confirmSelectUser = () => {
    addForm.value.user = selectedUser.value;
    selectUserDialogVisible.value = false;
};

</script>

<style scoped>
.search-box {
    padding: 10px 0px 10px 10px;
}
.table-box {
    padding-left: 10px;
}
.page-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
}

.select-user-dialog-content {
    display: flex;
    height: 400px;
}

.tree-container {
    width: 40%;
    border-right: 1px solid #eee;
    padding-right: 20px;
    overflow-y: auto;
}

.search-container {
    width: 60%;
    padding-left: 20px;
}

.search-input {
    margin-bottom: 20px;
}

.selected-user-info {
    margin-top: 20px;
}
</style>